const regeneratorRuntime = require("../../vendor/regenerator-runtime")
const co = require("../../vendor/co")
const share = require('../../utils/share.js')
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
Page({
    data: {
        isShowInfo: false,
        impress: false,
        // 聊天
        Identifier: '',
        UserSig: '',
        isPopMsg: false,
        msgNum: 0,
        isShowInfo: false
    },
    onLoad: function(options) {
        share(options)
        this.setData(options)

        function f() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    console.log("a")
                    resolve()
                }, 1000)
            })
        }

        co(function*() {
            for (var i = 0; i < 3; i++) {
                const r = yield f()
            }
            console.log('---')
        })
    },
    /**
     * 是否收起名片信息
     */
    checkShowInfo() {
        this.setData({
            isShowInfo: !this.data.isShowInfo
        })
    },
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.card.phone,
        })
    },
    /**
     * 复制内容
     */
    copyText(e) {
        var content = e.currentTarget.dataset.content
        wx.setClipboardData({
            data: content,
            success: res => {
                wx.getClipboardData({
                    success: res => {
                        wx.showToast({
                            icon: 'none',
                            title: '复制成功'
                        })
                    }
                })
            }
        })
    },
    /**
     * 保存至通讯录
     */
    saveContact() {
        let {
            card
        } = this.data
        wx.addPhoneContact({
            firstName: card.name, //名字
            mobilePhoneNumber: card.phone, //手机
            weChatNumber: card.wx_num, //微信
            addressStreet: card.address, //地址
            organization: card.company, //公司
            title: card.job, //职位
            email: card.email, //email
            success: function() {
                wx.showToast({
                    icon: 'success',
                    title: '保存成功',
                })
            }
        })
    },
    /**
     * 分享名片
     */
    shareTap() {
        this.setData({
            isShare: true
        })
    },

    /**
     *修改名片
     */
    toEditCard() {
        wx.navigateTo({
            url: '/pages/card/create-card'
        })
    },

    // posterTap() {
    //     wx.navigateTo({
    //         url: './poster?bg=' + this.data.card.img || this.data.info.images  + '&name=' + this.data.card.name + '&job=' + this.data.card.job + '&phone=' + this.data.card.phone + '&wx=' + this.data.card.wx_num + '&addr=' + this.data.card.address
    //     })
    // },
    onReady() {
        this.setData({
            imgSize: parseInt((getApp().window.width - 20) / 2)
        })
    },
    // 留言
    toTalk() {
        wx.navigateTo({
            url: '/pages/radar/wx-chat?id=ll' + this.data.info.id + '&name=' + this.data.info.nickname + '&face=' + this.data.info.images
        })
    },

    loadCard: function() {
        wx.showLoading({
            title: '加载中...',
        })
        const data = {
            id: this.data.station_id
        }
        // this.data.id && (data.id = this.data.id)
        getApp().http.get("city/member-card/card-detail?check_show=1", {
            data,
            showMsg: false
        }).then(res => {
            // wx.hideLoading()

            this.setData({
                mid: wx.getStorageSync("mid"),
                hasCard: res.data.is_has_card
            })
            if (this.data.mid != res.data.id) {
                //查看名片
                if (!res.data.info) {
                    wx.showModal({
                        title: '提示',
                        content: 'Ta还没有名片噢~',
                        showCancel: false,
                        confirmText: "我知道了",
                        success: res => {
                            wx.switchTab({
                                url: '/pages/find/index',
                            })
                        }
                    })
                    return
                }

            }
            if (!res.data.info.cityMemberCard) {
                wx.showModal({
                    title: '提示',
                    content: '您还没有名片哦',
                    confirmText: "去创建+",
                    cancelText: "我知道了",
                    success: res => {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '../card/create-card',
                            })
                        } else {
                            wx.switchTab({
                                url: '/pages/find/index',
                            })
                        }
                    }
                })
            } else {
                const card = res.data.info.cityMemberCard
                wx.setNavigationBarTitle({
                    title: res.data.info.nickname ? (res.data.info.nickname + "的微站") : "微站"
                })
                delete res.data.info.cityMemberCard
                this.setData({
                    isKeep: res.data.is_keep,
                    card,
                    info: res.data.info
                })
            }
        }).catch(err => {
            wx.showModal({
                title: '提示',
                content: err.message,
                showCancel: false,
                confirmText: "我知道了",
                success: res => {
                    wx.navigateBack({

                    })
                }
            })
        })
    },
    onShow() {
        if (this.data.id) {
            getApp().station_id = this.data.id
        }
        this.setData({
            station_id: getApp().station_id ? getApp().station_id : ''
        })
        let timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        this.setData({
            timestamp
        })

        this.loadCard();
        this.loadInfo()
        console.log(this.data.info, 'this.data.info.id')
        if (this.data.station_id != this.data.mid) {
            this.loadContact()
        }
        var listeners = {
            "onMsgNotify": (msg) => {
                webimhandler.onMsgNotify(msg, msgs => {
                    that.setData({
                        isPopMsg: true,
                        msgNum: this.data.msgNum + 1
                    })
                })
            }
        }
        webim.changeListener(listeners)
    },
    onHide() {
        if (this.data.id) {
            this.data.id = ''
            this.data.station_id = ''
        }
        this.uploadListener()
        getApp().http.post('city/tiny-station/save-customer-trail', {
            data: {
                time: this.data.timestamp,
                station_member_id: this.data.card.member_id ? this.data.card.member_id : '',
                action_type: 1
            }
        }).then(res => {})
    },
    onUnload() {
        this.uploadListener()
    },
    /**关闭监听 */
    uploadListener() {
        var listeners = {
            "status": 1
        }
        webim.changeListener(listeners)
    },
    loadInfo() {
        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.get('city/tiny-station/personal-data', {
            data: {
                member_id: this.data.station_id
            }
        }).then(res => {
            const articleInfo = res.data.article_info.articleData.slice(0, 5)
            const goodsInfo = res.data.goods_info.articleData.slice(0, 4)
            const impressionInfo = res.data.impression_info
            for (var i = 0; i < articleInfo.length; i++) {
                articleInfo[i].pic = articleInfo[i].articl_content.find(o => {
                    return !!o.images
                })
                console.log('123456')
            }
            var is_self;
            if (this.data.mid == wx.getStorageSync('mid')) {
                is_self = 0
            } else {
                is_self = 1
            }
            this.setData({
                articleInfo,
                goodsInfo,
                impressionInfo,
                is_self
            })
            wx.hideLoading()
        })
    },
    onInput(evt) {
        this.setData({
            content: evt.detail.value
        });
    },
    addImpress() {
        this.setData({
            impress: true
        })

    },
    bindImpress() {
        if (!this.data.content) {
            return
        }
        getApp().http.post('city/tiny-station/add-impression', {
            data: {
                name: this.data.content,
                member_id: this.data.station_id
            }
        }).then(res => {
            this.setData({
                impress: false
            })
            wx.showToast({
                title: '添加成功',
            })
            setTimeout(() => {
                this.loadInfo()

            }, 1000)
        })

    },
    cancelImpress() {
        this.setData({
            impress: false
        })
    },

    // /**
    //  * 我的名片夹
    //  */
    // cardList: function() {
    //     wx.redirectTo({
    //         url: 'card-list'
    //     })
    // },
    /**
     * 编辑名片
     */
    updateCard: function() {
        wx.navigateTo({
            url: 'create-card?id=' + this.data.info.id
        })
    },
    /**
     * 个人名片小程序码
     */
    // openQrcode: function() {
    //     var imgUrl = getApp().http.getBaseUrl() + "city/member-card/card-qrcode" + '?id=' + this.data.info.id;
    //     console.log(imgUrl)
    //     wx.previewImage({
    //         urls: [imgUrl],
    //     });
    // },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        console.log(!this.data.info, '!this.data.info')
        if (!this.data.info) {
            wx.switchTab({
                url: '/pages/find/index',
            })
            return
        }
        let t = '您好，这是我的名片,请惠存'
        if (this.data.info.id != this.data.mid) {
            t = `您好，这是${this.data.card.name || this.data.info.nickname}的名片,请惠存`
        }
        console.log('/pages/microStation/index?id=' + this.data.info.id + '&from=1')

        return {
            title: t,
            path: '/pages/microStation/index?id=' + this.data.info.id + '&from=1' + '&pmid=' + wx.getStorageSync('mid'),
        }
    },

    preImg(evt) {
        wx.previewImage({
            current: evt.currentTarget.dataset.img,
            urls: this.data.card.cityMemberCardImages.map(o => o.url),
        })
    },

    keep() {
        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.get("city/member-card/keep", {
            data: {
                id: this.data.card.id
            }
        }).then(res => {
            this.loadCard()
        })
    },

    save() {
        wx.addPhoneContact({
            firstName: this.data.card.name || this.data.info.nickname,
            mobilePhoneNumber: this.data.card.phone,
            organization: this.data.card.company,
            title: this.data.card.job,
            email: this.data.card.email
        })
    },
    // viewQr() {

    //     wx.previewImage({
    //         urls: [getApp().http.getBaseUrl() + "city/member-card/new-qr?id=" + this.data.card.id + "&sid=" + getApp().storeId],
    //     })

    //     return
    //     wx.showLoading({
    //         title: '加载中...',
    //     })
    //     getApp().http.get("city/member-card/qr", {
    //         data: {
    //             id: this.data.card.id
    //         }
    //     }).then(res => {
    //         wx.previewImage({
    //             urls: [res.data],
    //         })
    //         wx.hideLoading()
    //     })
    // },

    // like() {

    //     getApp().http.get("city/member-card/like", {
    //         data: {
    //             id: this.data.card.id
    //         }
    //     }).then(res => {
    //         let num = parseInt(this.data.card.like_num)
    //         if (res.data === true) {
    //             num--
    //             this.setData({
    //                 signNum: -1
    //             })
    //         } else {
    //             num++
    //             this.setData({
    //                 signNum: "+1"
    //             })
    //         }
    //         this.setData({
    //             "card.like_num": num
    //         })

    //         this.setData({
    //             isLike: true
    //         })
    //         clearTimeout(this.lid)
    //         this.lid = setTimeout(() => {
    //             this.setData({
    //                 isLike: false
    //             })
    //         }, 1000)
    //     })
    // },
    copy(evt) {
        const {
            t,
            val
        } = evt.currentTarget.dataset
        wx.showActionSheet({
            itemList: ['复制'],
            success: res => {
                wx.setClipboardData({
                    data: val,
                })
                wx.showToast({
                    title: t + "已复制",
                })
            }
        })
    },
    call(evt) {
        this.data.card.phone && wx.makePhoneCall({
            phoneNumber: this.data.card.phone,
        })
    },
    back() {
        const ps = getCurrentPages()
        if (ps.length == 1) {
            wx.redirectTo({
                url: '/pages/card/my-card',
            })
        } else {
            wx.navigateBack()
        }
    },
    openMap() {
        wx.openLocation({
            latitude: parseFloat(this.data.card.lat),
            longitude: parseFloat(this.data.card.lng),
            address: this.data.card.address
        })
    },
    action(evt) {
        const {
            path
        } = evt.currentTarget.dataset
        if (this.data.id && this.data.id != this.data.mid) {
            //查看别人的名片时
            if (!this.data.hasCard) {
                wx.showModal({
                    title: '提示',
                    content: '您需要先创建自己的名片哦',
                    cancelText: "我知道了",
                    confirmText: "去创建+",
                    success: res => {
                        res.confirm && wx.navigateTo({
                            url: '../card/create-card',
                        })
                    }
                })
            } else {
                wx.navigateTo({
                    url: path,
                })
            }
        } else {
            wx.navigateTo({
                url: path,
            })
        }
    },
    like() {
        getApp().http.get("city/member-card/like", {
            data: {
                id: this.data.card.id
            }
        }).then(res => {
            let num = parseInt(this.data.card.like_num)
            num += (res.data.status ? 1 : -1)
            this.setData({
                'card.like_num': num
            })
        })
    },
    /**
     * im
     */
    initIM: function() {
        var that = this;
        //当前用户身份
        var Config = {
            sdkappid: 1400114382,
            accountType: 31956,
            accountMode: 0 //帐号模式，0-表示独立模式，1-表示托管模式
        };
        var loginInfo = {
            'sdkAppID': Config.sdkappid, //用户所属应用id,必填
            'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
            'accountType': Config.accountType, //用户所属应用帐号类型，必填
            'identifier': 'll' + wx.getStorageSync('mid'), //当前用户ID,必须是否字符串类型，选填
            'identifierNick': wx.getStorageSync('user').nickName, //当前用户昵称，选填
            "headurl": wx.getStorageSync('user').avatarUrl,
            'userSig': that.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
            'loginPage': 1, //1表示名片页面进入,此页面进入不需要获取最近联系人，只需要登录,监听也不需要
        };
        var listeners = {
            "onMsgNotify": function(msg) {
                webimhandler.onMsgNotify(msg, function(msgs) {
                    // that.receiveMsgs(msgs);
                    that.setData({
                        isPopMsg: true,
                        msgNum: that.data.msgNum + 1
                    })
                })
            }
        }

        //其他对象，选填
        var options = {
            'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
            'isLogOn': false //是否开启控制台打印日志,默认开启，选填
        };
        //初始化了聊天对象，联系人页面设为-1，聊天页面设为相应的id
        webimhandler.init('ll' + this.data.station_id, 1)
        webimhandler.sdkLogin(loginInfo, listeners, options,
            //获取info后回掉，将所有联系人展示在页面上
            // function() {
            //     webimhandler.getCardUserUnread((msgNum) => {
            //         that.setData({
            //             isPopMsg: msgNum != 0 ? true : false,
            //             msgNum: msgNum
            //         })
            //     })
            // }
        );
    },
    loadContact() {
        getApp().http.post('city/tiny-station/login-im').then(q => {
            this.setData({
                UserSig: q.data.sig,
            })
            wx.stopPullDownRefresh()
            this.initIM();
        })
    },
})